#include "AddBlockWidget.h"
#include "ui_AddBlockWidget.h"
#include "../database/DatabaseManager.h"
#include <QMessageBox>
#include <QTimer>

AddBlockWidget::AddBlockWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::AddBlockWidget)
{
    ui->setupUi(this);
}

AddBlockWidget::~AddBlockWidget()
{
    delete ui;
}

void AddBlockWidget::init()
{
    DatabaseManager &manager = DatabaseManager::getInstance();
    QSqlDatabase db = manager.m_database;

    if (!db.isOpen()) {
        qWarning() << "数据库未连接";
        return;
    }

    QSqlQuery q(db);
    // 如果列名是 code，请把 mould_code 改为 code
    q.prepare("SELECT id, mould_code FROM Mould ORDER BY mould_code COLLATE NOCASE");
    if (!q.exec()) {
        qWarning() << "查询失败:" << q.lastError().text();
        return;
    }

    ui->comboBox->clear();
    while (q.next()) {
        const int id = q.value(0).toInt();
        const QString name = q.value(1).toString();
        ui->comboBox->addItem(name, id);               // 文本显示 name，userData 存 id
    }

    // 可选：默认不选中任何项
    ui->comboBox->setCurrentIndex(-1);
}

void AddBlockWidget::on_pushButton_clicked()
{
    if (ui->lineEdit->text().isEmpty()) {
        QMessageBox::warning(this, tr("输入错误"), tr("输入框不能为空！"));
        return;
    }

    DatabaseManager &manager = DatabaseManager::getInstance();
    QSqlDatabase db = manager.m_database;

    if (!manager.isConnected()) {
        QMessageBox::critical(this, tr("错误"), tr("数据库未连接！"));
        return;
    }

    int mouldId = ui->comboBox->currentData().toInt();
    if (mouldId <= 0) {
        QMessageBox::warning(this, tr("提示"), tr("没有模具。"));
        return;
    }

    QString blockCode = ui->lineEdit->text();
    int blockId = -1;

    QSqlQuery q(db);

    // 开启事务，保证一致性
    if (!db.transaction()) {
        QMessageBox::critical(this, tr("错误"), tr("开启事务失败：%1").arg(db.lastError().text()));
        return;
    }

    // 1) 查 Block 表
    q.prepare("SELECT id FROM Block WHERE block_code = ?");
    q.addBindValue(blockCode);
    if (!q.exec()) {
        db.rollback();
        QMessageBox::critical(this, tr("错误"), tr("查询 Block 失败：%1").arg(q.lastError().text()));
        return;
    }
    if (q.next()) {
        blockId = q.value(0).toInt();
    } else {
        // 2) 插入 Block
        q.prepare("INSERT INTO Block (block_code) VALUES (?)");
        q.addBindValue(blockCode);
        if (!q.exec()) {
            db.rollback();
            if (q.lastError().databaseText().contains("UNIQUE", Qt::CaseInsensitive)) {
                QMessageBox::information(this, tr("已存在"),
                                         tr("Block 表中已存在该编码。"));
            } else {
                QMessageBox::critical(this, tr("错误"),
                                      tr("插入 Block 失败：%1").arg(q.lastError().text()));
            }
            return;
        }
        blockId = q.lastInsertId().toInt();
    }

    // 3) 查 MouldBlock 是否已存在
    q.prepare("SELECT 1 FROM MouldBlock WHERE mould_id = ? AND block_id = ? LIMIT 1");
    q.addBindValue(mouldId);
    q.addBindValue(blockId);
    if (!q.exec()) {
        db.rollback();
        QMessageBox::critical(this, tr("错误"),
                              tr("查询 MouldBlock 失败：%1").arg(q.lastError().text()));
        return;
    }
    if (q.next()) {
        db.rollback();
        QMessageBox::information(this, tr("已存在"),
                                 tr("该模具下已存在相同的 Block。"));
        ui->lineEdit->clear();
        QTimer::singleShot(0, ui->lineEdit, [this]{ ui->lineEdit->setFocus(Qt::TabFocusReason); });
        return;
    }

    // 4) 插入 MouldBlock
    q.prepare("INSERT INTO MouldBlock (mould_id, block_id) VALUES (?, ?)");
    q.addBindValue(mouldId);
    q.addBindValue(blockId);
    if (!q.exec()) {
        db.rollback();
        QMessageBox::critical(this, tr("错误"),
                              tr("插入 MouldBlock 失败：%1").arg(q.lastError().text()));
        return;
    }

    // 提交事务
    if (!db.commit()) {
        db.rollback();
        QMessageBox::critical(this, tr("错误"), tr("提交事务失败：%1").arg(db.lastError().text()));
        return;
    }

    ui->lineEdit->clear();
}


